<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  <title>Disruptor | 推推蛋</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  
    <meta name="keywords" content="朱军函,大兄弟,chuck,BigBrother" />
  
  <meta name="description" content="SpringValidator校验参数： 1、验证bean，需要在参数前面加上@Valid，新增一个参数BindingResult，验证失败的信息会放里面 123456@PostMapping(&quot;&#x2F;test&#x2F;upload&quot;)public ResponseEntity&lt;Boolean&gt; tesupload(@Valid  @RequestBody">
<meta property="og:type" content="article">
<meta property="og:title" content="Disruptor">
<meta property="og:url" content="https://tuituidan.gitee.io/blog/2017/06/18/SpringValidator/index.html">
<meta property="og:site_name" content="推推蛋">
<meta property="og:description" content="SpringValidator校验参数： 1、验证bean，需要在参数前面加上@Valid，新增一个参数BindingResult，验证失败的信息会放里面 123456@PostMapping(&quot;&#x2F;test&#x2F;upload&quot;)public ResponseEntity&lt;Boolean&gt; tesupload(@Valid  @RequestBody">
<meta property="og:locale" content="zh">
<meta property="article:published_time" content="2017-06-17T16:00:00.000Z">
<meta property="article:modified_time" content="2020-06-25T09:08:45.155Z">
<meta property="article:author" content="推推蛋">
<meta property="article:tag" content="Disruptor">
<meta property="article:tag" content="RingBuffer">
<meta name="twitter:card" content="summary">
  
  
    <link rel="icon" href="/favicon.ico">
  
  <link href="//cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
  
<link rel="stylesheet" href="/css/style.css">

  
<script src="/js/pace.min.js"></script>

  

  
  

<meta name="generator" content="Hexo 4.2.1"></head>

<body>
  <div id="container">
      <header id="header">
    <div id="banner"></div>
    <div id="header-outer">
        <div id="header-menu" class="header-menu-pos animated">
            <div class="header-menu-container">
                <a href="/" class="left">
                    <span class="site-title">zhujunhan&#39;s Blog</span>
                </a>
                <nav id="header-menu-nav" class="right">
                    
                    <a  href="/">
                        <i class="fa fa-home"></i>
                        <span>首页</span>
                    </a>
                    
                    <a  href="/archives">
                        <i class="fa fa-archive"></i>
                        <span>归档</span>
                    </a>
                    
                    <a  href="/about">
                        <i class="fa fa-user"></i>
                        <span>关于</span>
                    </a>
                    
                </nav>
                <a class="mobile-header-menu-button">
                    <i class="fa fa-bars"></i>
                </a>
            </div>
        </div>
        <div id="header-row">
            <div id="logo">
                <a href="/">
                    <img src="/images/logo.jpg" alt="logo">
                </a>
            </div>
            <div class="header-info">
                <div id="header-title">
                    
                    <h2>
                        0 error 0 warning
                    </h2>
                    
                </div>
                <div id="header-description">
                    
                    <h3>
                        talk is cheap,show me the code
                    </h3>
                    
                </div>
            </div>
            <nav class="header-nav">
                <div class="social">
                    
                        <a title="home" target="_blank" href="//zhujunhan.github.io">
                            <i class="fa fa-home fa-2x"></i></a>
                    
                        <a title="github" target="_blank" href="//github.com/zhujunhan">
                            <i class="fa fa-github fa-2x"></i></a>
                    
                </div>
            </nav>
        </div>
    </div>
</header>
      <div class="outer">
        <section id="main" class="body-wrap"><article id="post-SpringValidator" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-inner">
    
      <header class="article-header">
        
  
    <h1 class="post-title" itemprop="name">
      Disruptor
    </h1>
    <div class="post-title-bar">
      <ul>
          
              <li>
                  <i class="fa fa-book"></i>
                  
                      <a href="/categories/Disruptor/">Disruptor</a>
                  
              </li>
          
        <li>
          <i class="fa fa-calendar"></i>  2017-06-18
        </li>
        <li>
          <i class="fa fa-eye"></i>
          <span id="busuanzi_value_page_pv"></span>
        </li>
      </ul>
    </div>
  

          
      </header>
    
    <div class="article-entry post-content" itemprop="articleBody">
      
            
            <p>SpringValidator校验参数：</p>
<p>1、验证bean，需要在参数前面加上@Valid，新增一个参数BindingResult，验证失败的信息会放里面</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">@PostMapping(&quot;&#x2F;test&#x2F;upload&quot;)</span><br><span class="line">public ResponseEntity&lt;Boolean&gt; tesupload(@Valid  @RequestBody FileInfo fileInfo, BindingResult bindingResult)&#123;</span><br><span class="line">   String errorMsg &#x3D;  bindingResult.getAllErrors().stream()</span><br><span class="line">           .map(ObjectError::getDefaultMessage).collect(Collectors.joining(&quot;,&quot;))</span><br><span class="line">    return ResponseEntity.ok(true);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后也可以不添加第二个参数，则验证失败会抛MethodArgumentNotValidException的异常，统一拦截处理</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">@RestControllerAdvice</span><br><span class="line">public class GlobalExceptionHandler &#123;</span><br><span class="line"></span><br><span class="line">    @ResponseStatus(value &#x3D; HttpStatus.BANDWIDTH_LIMIT_EXCEEDED)</span><br><span class="line">    @ExceptionHandler(value &#x3D; MethodArgumentNotValidException.class)</span><br><span class="line">    public String hander(MethodArgumentNotValidException ex)&#123;</span><br><span class="line">        return ex.getBindingResult().getAllErrors().stream().map(ObjectError::getDefaultMessage).collect(Collectors.joining(&quot;,&quot;));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>2、单个参数校验的时候，只是这样写是不生效的</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">@PostMapping(&quot;&#x2F;test&#x2F;upload1&quot;)</span><br><span class="line">public ResponseEntity&lt;Boolean&gt; tesupload(@NotBlank(message &#x3D; &quot;ss1 not be empty&quot;)  String ss)&#123;</span><br><span class="line"></span><br><span class="line">    return ResponseEntity.ok(true);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>需要在当前方法所属的controller类添加注解@Validated，且抛出的异常是ConstraintViolationException，所以两个都需要拦截单独处理</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">@ResponseStatus(value &#x3D; HttpStatus.BANDWIDTH_LIMIT_EXCEEDED)</span><br><span class="line">@ExceptionHandler(value &#x3D; ConstraintViolationException.class)</span><br><span class="line">public String hander(ConstraintViolationException ex)&#123;</span><br><span class="line"></span><br><span class="line">    return ex.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining(&quot;,&quot;));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>3、对于普通单字段验证，@NotNull，@NotBlank，@NotEmpty等等，如果两个字段有关联的，比如一个字段不为空的情况下另一个才不能为空，可以两个都为空，这种情况的解决办法有两种</p>
<p>第一种：添加一个新的注解</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">@Target(&#123;ElementType.TYPE&#125;)</span><br><span class="line">@Retention(RetentionPolicy.RUNTIME)</span><br><span class="line">public @interface GroupNotNull &#123;</span><br><span class="line">    String checkFieldName();</span><br><span class="line"></span><br><span class="line">    String dependentFieldName();</span><br><span class="line"></span><br><span class="line">    String message();</span><br><span class="line"></span><br><span class="line">    Class&lt;?&gt;[] groups() default &#123;&#125;;</span><br><span class="line"></span><br><span class="line">    Class&lt;? extends Payload&gt;[] payload() default &#123;&#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>实现注解的验证类</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">public class GroupNotNullValidator implements ConstraintValidator&lt;GroupNotNull, Object&gt; &#123;</span><br><span class="line"></span><br><span class="line">    private String checkFieldName;</span><br><span class="line"></span><br><span class="line">    private String dependentFieldName;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public void initialize(GroupNotNull constraintAnnotation) &#123;</span><br><span class="line">        this.checkFieldName &#x3D; constraintAnnotation.checkFieldName();</span><br><span class="line">        this.dependentFieldName &#x3D; constraintAnnotation.dependentFieldName();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) &#123;</span><br><span class="line">        if (null &#x3D;&#x3D; value) &#123;</span><br><span class="line">            return true;</span><br><span class="line">        &#125;</span><br><span class="line">        BeanWrapper beanWrapper &#x3D; new BeanWrapperImpl(value);</span><br><span class="line">        Object checkFieldValue &#x3D; beanWrapper.getPropertyValue(this.checkFieldName);</span><br><span class="line">        Object dependentFieldValue &#x3D; beanWrapper.getPropertyValue(this.dependentFieldName);</span><br><span class="line">        return !(null !&#x3D; dependentFieldValue &amp;&amp; null &#x3D;&#x3D; checkFieldValue);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后将注解放对应bean的class上</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">@GroupNotNull(checkFieldName &#x3D; &quot;chunkSize&quot;,dependentFieldName &#x3D; &quot;chunks&quot;,message &#x3D; &quot;必须指定&quot;)</span><br><span class="line">public class FileInfo &#123;</span><br><span class="line">    </span><br><span class="line">    private Integer chunk;</span><br><span class="line"></span><br><span class="line">    private Integer chunkSize;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>第二种方法：直接使用注解@ScriptAssert来实现</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">@ScriptAssert(lang &#x3D; &quot;javascript&quot;,script &#x3D; &quot;com.zjh.demo.entity.FileInfo.checkChucks(_this.userName,_this.chuck)&quot;,message &#x3D; &quot;username not be blank&quot;)</span><br><span class="line">public class FileInfo &#123;</span><br><span class="line"></span><br><span class="line">    private String userName;</span><br><span class="line">    </span><br><span class="line">    private String chuck;</span><br><span class="line"></span><br><span class="line">    public static boolean checkChucks(String username,String mychuck)&#123;</span><br><span class="line">        return !(mychuck!&#x3D;null&amp;&amp;username&#x3D;&#x3D;null);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>@ScriptAssert的lang参数是javascript，不知道为啥，script参数是指定调用的方法，方法得是个静态方法，_this应该是表示当前对象实例，传入该方法进行验证</p>
<p>这两种方法验证失败也都是抛MethodArgumentNotValidException异常</p>

            <div class="post-copyright">
    <div class="content">
        <p>最后更新： 2020年06月25日 17:08</p>
        <p>原始链接： <a class="post-url" href="/2017/06/18/SpringValidator/" title="Disruptor">https://tuituidan.gitee.io/blog/2017/06/18/SpringValidator/</a></p>
        <footer>
            <a href="https://tuituidan.gitee.io/blog">
                <img src="/images/logo.jpg" alt="推推蛋">
                推推蛋
            </a>
        </footer>
    </div>
</div>

      
        
            
<div class="page-reward">
    <a id="rewardBtn" href="javascript:;">赏</a>
</div>

<div id="reward" class="post-modal reward-lay">
    <a class="close" href="javascript:;" id="reward-close">×</a>
    <span class="reward-title">
        <i class="icon icon-quote-left"></i>
        有用就请我喝咖啡吧
        <i class="icon icon-quote-right"></i>
    </span>
    <div class="reward-content">
        
        <div class="reward-code">
            <img id="rewardCode" src="/images/wechat_code.jpg" alt="打赏二维码">
        </div>
        <div class="reward-select">
            
            <label class="reward-select-item checked" data-id="wechat" data-wechat="/images/wechat_code.jpg">
                <img class="reward-select-item-wechat" src="/images/wechat.png" alt="微信">
            </label>
            
            
            <label class="reward-select-item" data-id="alipay" data-alipay="/images/alipay_code.jpg">
                <img class="reward-select-item-alipay" src="/images/alipay.png" alt="支付宝">
            </label>
            
        </div>
    </div>
</div>


        
    </div>
    <footer class="article-footer">
        
        
<div class="post-share">
    <a href="javascript:;" id="share-sub" class="post-share-fab">
        <i class="fa fa-share-alt"></i>
    </a>
    <div class="post-share-list" id="share-list">
        <ul class="share-icons">
          <li>
            <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=https://tuituidan.gitee.io/blog/2017/06/18/SpringValidator/&title=《Disruptor》 — 推推蛋&pic=cover_picture/disruptor.png" data-title="微博">
              <i class="fa fa-weibo"></i>
            </a>
          </li>
          <li>
            <a class="weixin share-sns" id="wxFab" href="javascript:;" data-title="微信">
              <i class="fa fa-weixin"></i>
            </a>
          </li>
          <li>
            <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=https://tuituidan.gitee.io/blog/2017/06/18/SpringValidator/&title=《Disruptor》 — 推推蛋&source=" data-title="QQ">
              <i class="fa fa-qq"></i>
            </a>
          </li>
          <li>
            <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=https://tuituidan.gitee.io/blog/2017/06/18/SpringValidator/" data-title="Facebook">
              <i class="fa fa-facebook"></i>
            </a>
          </li>
          <li>
            <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《Disruptor》 — 推推蛋&url=https://tuituidan.gitee.io/blog/2017/06/18/SpringValidator/&via=https://tuituidan.gitee.io/blog" data-title="Twitter">
              <i class="fa fa-twitter"></i>
            </a>
          </li>
          <li>
            <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=https://tuituidan.gitee.io/blog/2017/06/18/SpringValidator/" data-title="Google+">
              <i class="fa fa-google-plus"></i>
            </a>
          </li>
        </ul>
     </div>
</div>
<div class="post-modal wx-share" id="wxShare">
    <a class="close" href="javascript:;" id="wxShare-close">×</a>
    <p>扫一扫，分享到微信</p>
    <img src="//api.qrserver.com/v1/create-qr-code/?data=https://tuituidan.gitee.io/blog/2017/06/18/SpringValidator/" alt="微信分享二维码">
</div>

<div class="mask"></div>

        
        <ul class="article-footer-menu">
            
            
  <li class="article-footer-tags">
    <i class="fa fa-tags"></i>
      
    <a href="/tags/Disruptor/" class="color5">Disruptor</a>
      
    <a href="/tags/RingBuffer/" class="color1">RingBuffer</a>
      
  </li>

        </ul>
        
    </footer>
  </div>
</article>



<nav id="article-nav">
  
    <a href="/2017/06/18/Disruptor/" id="article-nav-newer" class="article-nav-link-wrap">

      <span class="article-nav-title">
        <i class="fa fa-hand-o-left" aria-hidden="true"></i>
        
          Disruptor
        
      </span>
    </a>
  
  
</nav>



    
        <link rel="stylesheet" href="//unpkg.com/gitment/style/default.css">
    <script src="//unpkg.com/gitment/dist/gitment.browser.js"></script>
    <div id="comments">
        <script>
            var gitment = new Gitment({
                owner: 'zhujunhan',
                repo: 'zhujunhan.github.io',
                oauth: {
                    client_id: 'c2c63d0ea4d9d2d02a69',
                    client_secret: '453c28c988d7d00d5b81d1b3f703295b809d5500',
                },
            })
            gitment.render('comments')
        </script>
    </div>

    
</section>
        
      </div>
      <footer id="footer">
  <div class="outer">
    <div id="footer-info" class="inner">
      
<p>
    <span id="busuanzi_container_site_uv" style='display:none'>
        总访客数：<span id="busuanzi_value_site_uv"></span>
    </span>
    <span id="busuanzi_container_site_pv" style='display:none'>
        总访问量：<span id="busuanzi_value_site_pv"></span>
    </span>
</p>


      <p>
        Copyright
      &copy; 2020 推推蛋<br>
      </p>
    </div>
  </div>
</footer>
    <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<script src="//cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script>
  var mihoConfig = {
      root: "https://tuituidan.gitee.io/blog",
      animate: true,
      isHome: false,
      share: true,
      reward: 1
  }
</script>
<div class="sidebar">
    <div id="sidebar-search" title="Search">
        <i class="fa fa-search"></i>
    </div>
    <div id="sidebar-category" title="Categories">
        <i class="fa fa-book"></i>
    </div>
    <div id="sidebar-tag" title="Tags">
        <i class="fa fa-tags"></i>
    </div>
    <div id="sidebar-top">
        <span class="sidebar-top-icon"><i class="fa fa-angle-up"></i></span>
    </div>
</div>
<div class="sidebar-menu-box" id="sidebar-menu-box">
    <div class="sidebar-menu-box-container">
        <div id="sidebar-menu-box-categories">
            <a class="category-link" href="/categories/Disruptor/">Disruptor</a><a class="category-link" href="/categories/%E5%89%8D%E7%AB%AF/">前端</a>
        </div>
        <div id="sidebar-menu-box-tags">
            <a href="/tags/Disruptor/" style="font-size: 20px;">Disruptor</a> <a href="/tags/RingBuffer/" style="font-size: 20px;">RingBuffer</a> <a href="/tags/webuploader/" style="font-size: 10px;">webuploader</a> <a href="/tags/%E5%89%8D%E7%AB%AF/" style="font-size: 10px;">前端</a>
        </div>
    </div>
    <a href="javascript:;" class="sidebar-menu-box-close">&times;</a>
</div>
<div class="mobile-header-menu-nav" id="mobile-header-menu-nav">
    <div class="mobile-header-menu-container">
        <span class="title">菜单</span>
        <ul class="mobile-header-menu-navbar">
            
            <li>
                <a  href="/">
                    <i class="fa fa-home"></i><span>首页</span>
                </a>
            </li>
            
            <li>
                <a  href="/archives">
                    <i class="fa fa-archive"></i><span>归档</span>
                </a>
            </li>
            
            <li>
                <a  href="/about">
                    <i class="fa fa-user"></i><span>关于</span>
                </a>
            </li>
            
        </ul>
    </div>
    <div class="mobile-header-tag-container">
        <span class="title">标签</span>
        <div id="mobile-header-container-tags">
            <a href="/tags/Disruptor/" style="font-size: 20px;">Disruptor</a> <a href="/tags/RingBuffer/" style="font-size: 20px;">RingBuffer</a> <a href="/tags/webuploader/" style="font-size: 10px;">webuploader</a> <a href="/tags/%E5%89%8D%E7%AB%AF/" style="font-size: 10px;">前端</a>
        </div>
    </div>
</div>
<div class="search-wrap">
    <span class="search-close">&times;</span>
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="back">
            <i class="icon icon-lg icon-chevron-left"></i>
        </a>
        <input class="search-field" placeholder="搜索..." id="keywords">
        <a id="search-submit" href="javascript:;">
            <i class="fa fa-search"></i>
        </a>
    <div class="search-container" id="search-container">
        <ul class="search-result" id="search-result">
        </ul>
    </div>
</div>

<div id="search-tpl">
    <li class="search-result-item">
        <a href="{url}" class="search-item-li">
            <span class="search-item-li-title" title="{title}">{title}</span>
        </a>
    </li>
</div>

<script src="/js/search.js"></script>


<script src="/js/main.js"></script>









  
<link rel="stylesheet" href="//cdn.bootcss.com/animate.css/3.5.0/animate.min.css">

  <script src="//cdn.bootcss.com/scrollReveal.js/3.0.5/scrollreveal.js"></script>
  
<script src="/js/animate.js"></script>



  
<script src="/js/pop-img.js"></script>

  <script>
     $(".article-entry p img").popImg();
  </script>

  </div>
</body>
</html>